package common

import (
	"fmt"
	"reflect"
	"strings"
)

type Form interface {
	Data() map[string]interface{}
	IsValid() bool
}

type BaseForm struct {
	Fields   interface{}
	JSONData map[string]interface{}
}

func NewBaseForm(Fields interface{}, JSONData map[string]interface{}) *BaseForm {
	return &BaseForm{JSONData: JSONData, Fields: Fields}
}

func (self *BaseForm) Data(exceptFields map[string]int) map[string]interface{} {
	if self.IsValid(exceptFields) {
		return self.JSONData
	}
	return map[string]interface{}{}
}

func (self *BaseForm) IsValid(exceptFields map[string]int) bool {
	GetType := reflect.TypeOf(self.Fields)
	fieldsNumber := GetType.NumField()
	pointer := reflect.ValueOf(&self.Fields)
	ele := pointer.Elem()
	for index := 0; index < fieldsNumber; index++ {
		field := GetType.Field(index)
		_, exceptError := exceptFields[strings.ToLower(field.Name)]
		if exceptError {
			continue
		}
		value, error := self.JSONData[strings.ToLower(field.Name)]
		fmt.Println(value)
		fmt.Println(field.Name)
		if !error {
			return false
		}

		ele.FieldByName(field.Name).Set(reflect.ValueOf(value))
	}
	return true
}
